#include "NeoToggleButton.h"
#include "private/NeoToggleButtonPrivate.h"
#include <QMouseEvent>
#include <QPropertyAnimation>

NEO_PUBLIC_PROPERTY_CREATE_NOTIFY_CPP(NeoToggleButton, bool, Checked)
NEO_PUBLIC_PROPERTY_CREATE_NOTIFY_CPP(NeoToggleButton, NeoIconType::FontAwesomeSolid, Icon)
NEO_PUBLIC_PROPERTY_CREATE_NOTIFY_CPP(NeoToggleButton, QString, Text)
NEO_PUBLIC_PROPERTY_CREATE_CPP(NeoToggleButton, bool, IsAnimationEnabled)
NEO_PUBLIC_PROPERTY_CREATE_CPP(NeoToggleButton, QColor, NormalBackgroundColor)
NEO_PUBLIC_PROPERTY_CREATE_CPP(NeoToggleButton, QColor, CheckedBackgroundColor)
NEO_PUBLIC_PROPERTY_CREATE_CPP(NeoToggleButton, QColor, NormalForegroundColor)
NEO_PUBLIC_PROPERTY_CREATE_CPP(NeoToggleButton, QColor, CheckedForegroundColor)

NeoToggleButton::NeoToggleButton(QWidget *parent)
    : QWidget(parent), d_ptr(new NeoToggleButtonPrivate())
{
    NEO_PUBLIC_POINT(NeoToggleButton)
    d->q_ptr = this;
    connect(d->pBackgroundColorAnimation, &QPropertyAnimation::valueChanged, this, [this]()
            { this->update(); });
    connect(d->pBackgroundColorAnimation, &QPropertyAnimation::finished, this, [this]()
            {
        NEO_PUBLIC_POINT(NeoToggleButton)
        this->setChecked(!d->pChecked); });
}

NeoToggleButton::NeoToggleButton(const QString &text, QWidget *parent)
    : NeoToggleButton(parent)
{
    setText(text);
}

NeoToggleButton::NeoToggleButton(NeoIconType::FontAwesomeSolid icon, QWidget *parent)
    : NeoToggleButton(parent)
{
    setIcon(icon);
}

NeoToggleButton::~NeoToggleButton() = default;

void NeoToggleButton::mousePressEvent(QMouseEvent *event)
{
    NEO_PUBLIC_POINT(NeoToggleButton)
    if (event->button() == Qt::LeftButton)
    {
        if (d->pIsAnimationEnabled)
        {
            d->startColorAnimation();
        }
        else
        {
            this->setChecked(!d->pChecked);
        }
        event->accept();
        return;
    }
    return QWidget::mousePressEvent(event);
}

void NeoToggleButton::mouseReleaseEvent(QMouseEvent *event)
{
    NEO_PUBLIC_POINT(NeoToggleButton)
    if (event->button() == Qt::LeftButton)
    {
        event->accept();
        return;
    }
    return QWidget::mouseReleaseEvent(event);
}

void NeoToggleButton::paintEvent(QPaintEvent *event)
{
    NEO_PUBLIC_POINT(NeoToggleButton)
    NEO_PAINTER_RESET
    d->drawBackground(&painter);
    d->drawIcon(&painter);
    d->drawText(&painter);
}